package com.lwb.educenter.controller;

import com.google.gson.Gson;
import com.lwb.commonutils.JwtUtils;
import com.lwb.educenter.entity.UcenterMember;
import com.lwb.educenter.service.UcenterMemberService;
import com.lwb.educenter.utils.ConstantWxUtils;
import com.lwb.educenter.utils.HttpClientUtils;
import com.lwb.serviceBase.StudyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Controller//注意这里没有配置 @RestController
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    @GetMapping("login")
    public String genQrConnect(HttpSession session) {

        // 微信开放平台授权baseUrl
        //%s相当于？占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //对redirect_url进行URLEncoder编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try{
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        }catch (Exception e){

        }

        //设置%s中的值
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "state"
        );
        //重定向到请求微信地址
        return "redirect:"+url;
    }

    //回调函数
    @GetMapping("callback")
    public String callback(String code,String state){
        System.out.println("code:"+code+" "+"state:"+state);
        try{
        //1. 获取code的值，临时票据，类似于验证码
        // 2. 拿着code请求微信固定地址，得到两个值access_token和openid
            // 微信开放平台授权baseUrl
            //%s相当于？占位符
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接参数
            String tokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code);
            //请求这个拼接好的地址
            //使用HttpClient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(tokenUrl);

            //accessTokenInfo字符串转换成map集合，根据map里面key获取对应值
            //使用json转换工具Gson
            Gson gson = new Gson();
            HashMap accessTokenMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) accessTokenMap.get("access_token");
            String openid = (String) accessTokenMap.get("openid");
            System.out.println("access_token: "+access_token+"openid: "+openid);
            //根据openid进行查询，看数据库中是否已经有数据
            UcenterMember ucenterMember = ucenterMemberService.getMemberByOpenId(openid);
            if (ucenterMember == null){
                //3. 拿到access_token 和 openid，再去请求微信提供固定的地址，获取到扫描人信息
                //访问微信资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                //发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");
                ucenterMember = new UcenterMember();
                ucenterMember.setOpenid(openid);
                ucenterMember.setNickname(nickname);
                ucenterMember.setAvatar(headimgurl);
                ucenterMemberService.save(ucenterMember);
            }

            String jwtToken = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());

            return "redirect:http://localhost:3000?token="+jwtToken;
        }catch (Exception e){
            throw new StudyException(20001,"系统出错误！！");
        }


    }
}
